#-*- coding: utf-8 -*-

"""
    Copyright 2010 
    Kacper Żuk <kacper.b.zuk@gmail.com>
    Maciej 'Dreydahh' Winkler <666@dreydahh.pl>
    
    This file is part of Urh Dungeon 2.

    Urh Dungeon 2 is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Urh Dungeon 2 is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Urh Dungeon 2.  If not, see <http://www.gnu.org/licenses/>.
"""

import pygame, cPickle, os
import vars, colors
from random import *
from functions import *
from pygame.locals import *
from lang import *
lang = langs[vars.language]

class bigSprite():
    def __init__(self, parent, pos):
        self.x, self.y = pos
        self.parent = parent
        i = 0
        while images.__contains__(str(i)):
            i += 1
        images[str(i)] = None
        self.sprite = str(i)
        self.type = "bigSprite"
        try:
            self.parent.children.append(self)
        except AttributeError:
            self.parent.children = [self]

    def update(self):
        if not vars.dung.get(self.parent.x, self.parent.y) == self.parent:
            vars.dung.set(floor(vars.dung.floor), self.x, self.y)
            self = floor(vars.dung.floor)
            
    def msgBox(self, pos):
        return self.parent.msgBox(pos)
        
    def click(self):
        self.parent.click()
        
class box(pygame.sprite.Sprite):
    def __init__(self, object, coor, answers):
        pygame.sprite.Sprite.__init__(self, self.groups)
        self.object = object
        if not self.object.type == "readbook":
            self.rect = pygame.Rect(coor[0], coor[1], 200, 175)
        else:
            self.rect = pygame.Rect(coor[0], coor[1], 250, 300)
        self.answers = answers
        #[reading]
        if self.object.type == "readbook":
            self.image = img('book').copy()
            self.scrollup = pygame.Rect(coor[0]+225, coor[1]+17, 10, 14)
            self.scrolldown = pygame.Rect(coor[0]+225, coor[1]+257, 10, 14)
        else:
            self.image = img('box').copy()
        #[/reading]
        
        if not self.object.type == "readbook":
            printSurface(self.image, lang[self.object.name].upper(), 10, (255,255,255), (100, 10), True)
        else:
            printSurface(self.image, lang[self.object.name].upper(), 10, (255,255,255), (125, 10), True)
        
        ## ITEM INFO ##
        if not self.object.type == "readbook":
            self.image.blit(img(object.sprite), img(object.sprite).get_rect(center=(25, 65)))
        
        if self.object.type == "lock":
            printSurface(self.image, lang['openPass'], 9, (255,255,255), (50,25))
            printSurface(self.image, lang['uHaveToKill'], 9, (255,255,255), (50,45))
            i = 0
            for ob in object.ob:
                if vars.dung.get(ob.x,ob.y) == ob:
                    i += 1
                    printSurface(self.image, lang[ob.name], 9, (255,255,255), (50,45+15*i))

        elif self.object.type == "chest":
            printSurface(self.image, lang['content'], 9, (255,255,255), (80, 24))
            if self.object.item:
                self.image.blit(img(self.object.item.sprite),(45,50))
                printSurface(self.image, lang[self.object.item.name], 9, (255,255,255), (80,40))
                printSurface(self.image, lang['damage']+str(self.object.item.power), 9, (255,255,255), (80,55))
                printSurface(self.image, lang['reqStr']+str(self.object.item.str), 9, (255,255,255), (80,65))
                printSurface(self.image, lang['reqDex']+str(self.object.item.dex), 9, (255,255,255), (80,75))
            else:
                printSurface(self.image, lang['empty'], 9, (255,255,255), (80,55))

        elif self.object == vars.player:
            printSurface(self.image, lang['lvl']+str(self.object.lvl), 9, (255, 255, 255), (50,35))
            printSurface(self.image, lang['hp']+str(self.object.hp)+"/"+str(self.object.maxhp), 9, (255, 255, 255), (50,50))
            printSurface(self.image, lang['str']+str(self.object.str), 9, (255, 255, 255), (50,65))
            printSurface(self.image, lang['dex']+str(self.object.dex), 9, (255, 255, 255), (50,80))

            if vars.player.sp > 0:
                [ printSurface(self.image, '+', 9, (255,255,255), (175,50+15*i)) for i in range(3) ]
            
            printSurface(self.image, lang['sp']+str(self.object.sp), 9, (255, 255, 255), (50,95))
            
        elif self.object.type == "char":
            printSurface(self.image, lang['lvl']+str(self.object.lvl), 9, (255, 255, 255), (70,35))
            printSurface(self.image, lang['hp']+str(self.object.hp), 9, (255, 255, 255), (70,50))
            printSurface(self.image, lang['str']+str(self.object.str), 9, (255, 255, 255), (70,65))
            printSurface(self.image, lang['dex']+str(self.object.dex), 9, (255, 255, 255), (70,80))

        elif self.object.type == "weapon":
            printSurface(self.image, lang['damage']+str(self.object.power), 9, (255, 255, 255), (50,40))
            
        elif self.object.type == "armor" or self.object.type == "head":
            printSurface(self.image, lang['def']+str(self.object.power), 9, (255, 255, 255), (50,40))
            
        elif self.object.type == "pot":
            printSurface(self.image, lang['potRecover'], 9, (255, 255, 255), (50,50))
            printSurface(self.image, lang['70hp'], 9, (255, 255, 255), (50,70))
        #[reading]
        elif self.object.type == "readbook":
            rect = pygame.Rect(coor[0]+20, coor[1]+25, 190, 255)
            size = 10
            font = pygame.font.Font(vars.font, size)
            lines = fitInRect(lang[self.object.msg], font, rect)
            x = 0
            offset = 20
            for msg in lines[vars.startline:]:
                if x*(size+5)+offset >= rect.h:
                    break
                printSurface(self.image, msg, size, colors.grey, (35, x*(size+5)+offset))
                x+= 1
        #[/reading]
        if self.object.type == "armor" or self.object.type == "head" or self.object.type == "weapon":
            printSurface(self.image, lang['reqStr']+str(self.object.str), 9, (255, 255, 255), (50,60))
            printSurface(self.image, lang['reqDex']+str(self.object.dex), 9, (255, 255, 255), (50,80))
            
        ## Answers ##
        n = 0
        if len(self.answers) > 2:
            x = 15
        else:
            x = 25

        for ans in self.answers:
            if self.object.type == "readbook":
                printSurface(self.image, lang[ans], 10, (255,255,255), (125,255+x*n), True)
            else:
                printSurface(self.image, lang[ans], 10, (255,255,255), (100,132+x*n), True)
            n += 1

    def draw(self, dest):
        dest.blit(self.image, self.rect)
        if self.rect.x + self.rect.w > 22*32:
            new = pygame.Surface((22*32-self.rect.x,175), pygame.SRCALPHA)
            new.blit(self.image, (0,0))
            self.image = new

    def click(self, coor):
        coor = (coor[0] - self.rect.x, coor[1] - self.rect.y)
        if len(self.answers) == 2:
            if not self.object.type == "readbook":
                rects = [pygame.Rect(0, 120, 200, 25), pygame.Rect(0, 146, 200, 25)]
            else: 
                rects = [pygame.Rect(0, 0, 0, 0), pygame.Rect(0, 275, 250, 25)]#first is null cause not used
        else: #book would have only 1 option
            rects = [pygame.Rect(0, 120, 200, 18), pygame.Rect(0, 138, 200, 18), pygame.Rect(0, 156, 200, 20)]
        i = 0
        statrects = [pygame.Rect(173,50,10,10), pygame.Rect(173,65,10,10), pygame.Rect(173,80,10,10)]
        if vars.debug:
            for rec in statrects + rects:
                pygame.draw.line(self.image, (200,200,200), (rec.x,rec.y), (rec.x+rec.w,rec.y))
                pygame.draw.line(self.image, (200,200,200), (rec.x,rec.y), (rec.x,rec.y+rec.h))
                pygame.draw.line(self.image, (200,200,200), (rec.x+rec.w,rec.y), (rec.x+rec.w,rec.y+rec.h))
                pygame.draw.line(self.image, (200,200,200), (rec.x,rec.y+rec.h), (rec.x+rec.w,rec.y+rec.h))
        action = False
        for ans in rects:
            if ans.collidepoint(coor):
                action = self.answers[i]
                break
            i += 1
        if action:
            self.clear()
            if action == 'cancel':
                self.clear()
            elif action == 'take' or action == 'equip' or action == 'unequip' or action == 'destroy':
                self.object.click(action)
            elif action == 'drink':
                self.object.click()
            elif action == 'kill':
                if not vars.player.infight:
                    vars.player.infight = self.object
                else:
                    printConsole(lang['inFight'], (150,150,150))
            else:
                printConsole("Action not implemented: "+action, (100,100,255))
        refresh = False
        if self.object == vars.player:
            if vars.player.sp > 0:
                i = 0
                for rec in statrects:
                    if rec.collidepoint(coor):
                        refresh = True
                        if i == 0:   # add hp
                            add = vars.player.lvl/3
                            if add < 1:
                                add = 1
                            #vars.player.hp += add #sp is upgrading only maxhp
                            vars.player.maxhp += add
                            vars.player.sp -= 1
                            printConsole(lang['trainHp'], colors.green)
                        elif i == 1:   #add str
                            vars.player.str += 1
                            vars.player.sp -= 1
                            printConsole(lang['trainStr'], colors.green)
                        elif i == 2:   #add dex
                            vars.player.dex += 1
                            vars.player.sp -= 1
                            printConsole(lang['trainDex'], colors.green)
                    i += 1
        #[reading]
        elif self.object.type == "readbook": 
            coor = (coor[0] + self.rect.x, coor[1] + self.rect.y)
            if self.scrollup.collidepoint(coor) and not vars.startline <= 0:
                vars.startline -= 1
                refresh = True
            if self.scrolldown.collidepoint(coor):
                vars.startline += 1
                refresh = True
        #[/reading]
        if refresh:
            self.clear()
            self = box(self.object, (self.rect[0], self.rect[1]), self.answers)

    def clear(self):
        #[reading]
        vars.linestart = 0
        #[/reading]
        vars.panelupdate = True
        self.kill()
        self.groups[1].empty()

class stdout():
    def write(self, txt):
        txt = txt.strip()
        if txt:
            txt = txt.split(" ")
            for t in txt:
                printConsole(t, (255,255,255))
        
class hack():
    def __init__(self):
        self.command = str()
        self.on = False
        self.prev = ""
        
    def add(self, key):
        if key == "space":
            key = " "
        elif key == "backspace":
            self.command = self.command[:-1]
            key = ""
        self.command += key
        
    def execute(self):
        try:
            exec(self.command)
        except:
            asd = sys.exc_info()[1].args[0]
            printConsole("Error: "+asd, (255,10,10))
        self.prev = self.command
        self.command = ""
        
    def draw(self, dest):
        printSurface(dest, "> "+self.command, 10, (200,200,200), (40, 0), False, colors.black)
        
class item():
    def __init__(self, name, power, str, dex, sprite, type):
        self.name = name
        self.power = power
        self.str = str
        self.dex = dex
        self.sprite = sprite
        self.type = type
        
    def msgBox(self, coor, src):
        if src == 'eq':
            box(self, coor, ['unequip', 'cancel'])
        else:
            box(self, coor, ['equip', 'destroy', 'cancel'])

    def click(self, action):
        vars.panelupdate = True
        if action == 'unequip':
            if len(vars.player.backbag) < 6:
                vars.player.backbag.append(self)
                vars.player.eq[self.type] = False
            else:
                printConsole(lang['fullBB'],(255,20,20))
        elif action == 'equip':
            if vars.player.eq[self.type]:
                vars.player.backbag.append(vars.player.eq[self.type])
            vars.player.backbag.remove(self)
            vars.player.eq[self.type] = self
        elif action == 'destroy':
            vars.player.backbag.remove(self)
                
class chest():
    def __init__(self, item, sprite):
        self.type = "chest"
        self.name = 'chest'
        self.item = item
        self.sprite = sprite
        self.x = 0
        self.y = 0
        
    def open(self):
        self.sprite = self.sprite[:-1]+"o"
        vars.dung.regenerate()
        
    def take(self, char):
        if len(char.backbag) < 9 and self.item:
            char.backbag.append(self.item)
            self.item = False

    def click(self, dung=None):
        vars.panelupdate = True
        self.open()
        self.take(vars.player)
        
    def msgBox(self, coor):
        self.open()
        box(self, coor, ['take', 'cancel'])
            
class potion():
    def __init__(self, sprite="pot"):
        self.type = "pot"
        self.name = 'potion'
        self.sprite = sprite
        
    def drink(self, char):
        char.hp += int(char.maxhp*0.7)
        if char.hp > char.maxhp:
            char.hp = char.maxhp
        printConsole(lang['recover']+str(int(char.maxhp*0.7)), colors.drinkPotion)
        char.potions.remove(self)
        
    def msgBox(self, coor, src):
        if src == 'dung':
            box(self, coor, ['take', 'cancel'])
        else:
            box(self, coor, ['drink', 'cancel'])

    def click(self, dung = False):
        vars.panelupdate = True
        if dung:
            if len(vars.player.potions) < 3:
                vars.player.potions.append(self)
                vars.dung.set(floor(vars.dung.floor), self.x, self.y)
                vars.dung.img = vars.dung.regenerate()
            else:
                printConsole(lang['fullPot'], (255,20,20))
        else:
            if not vars.player.hp == vars.player.maxhp:
                self.drink(vars.player)
            else:
                printConsole(lang['fullHP'], (255,20,20))

class player(pygame.sprite.Sprite):
    def __init__(self, name, sprite):
        pygame.sprite.Sprite.__init__(self, self.groups)
        self.name = name
        self.sprite = sprite
        self.sp = 0   #stat points
        self.x = 1
        self.y = 1
        self.lvl = 1
        self.exp = 0
        #self.nextlvl = ((self.lvl+1)*20*self.lvl/3)
        self.str = 10
        self.dex = 10
        self.hp = 10
        self.maxhp = 10
        self.counter = 0
        self.type = "char"
        self.eq = {"head": False,
                   "armor": item('shirt', 10, 10, 10, "shirt", "armor"),
                   "weapon": item('knife', 10, 10, 10, "knife", "weapon")}
        self.backbag = list()
        self.potions = list()
        self.gold = 0
        self.spritenum = 1
        self.movanix = 0
        self.movaniy = 0
        self.direction = 'd'
        self.infight = False
        self.fightcounter = 0
        
    def update(self):
        if not self.movanix and not self.movaniy and self.infight:
            self.fightcounter += 1
            if self.fightcounter == 25:
                dmg = self.attack(self.infight)
                if not dmg:
                    printConsole(lang[self.name]+lang['missed'], colors.yellow)
                elif dmg == 'dead':
                    vars.dung.set(floor(vars.dung.floor), self.infight.x, self.infight.y)
                    printConsole(lang[self.name]+lang['killed']+lang[self.infight.name], colors.green)
                    
                    #[gold sys]
                    gold = int(random()*self.infight.gold)
                    if vars.player.gold+gold < vars.goldmax:
                        printConsole(lang['gain']+str(gold)+lang['gold'], colors.green)
                        vars.player.gold += gold
                    else:
                        vars.player.gold = vars.goldmax
                    #[/gold sys]

                    self.infight = False
                    #exp sys
                    if self.exp >= (self.lvl+1)*20*self.lvl/3:
                        self.lvl += 1
                        self.sp += 5
                        vars.player.maxhp += vars.player.lvl*(vars.player.lvl%3)
                        vars.player.hp = vars.player.maxhp
                        printConsole(lang['gain']+str(self.lvl)+lang['lvlGain'], colors.white)
                else:
                    printConsole(lang[self.name]+lang['hitted']+lang[self.infight.name]+lang['for']+str(dmg), colors.green)
            elif self.fightcounter == 50:
                self.fightcounter = 0
                dmg = self.infight.attack(self)
                if not dmg:
                    printConsole(lang[self.infight.name]+lang['missed'], colors.green)
                elif dmg == 'dead':
                    ## GAME OVER ##
                    vars.gameover = True
                    try:
                        os.unlink('save.upf')
                    except OSError:
                        pass
                    printConsole(lang[self.infight.name]+lang['killed']+lang[self.name], colors.red)
                else:
                    printConsole(lang[self.infight.name]+lang['hitted']+lang[self.name]+lang['for']+str(dmg), colors.red)
                
        else:
            self.counter += 1
            if self.movanix or self.movaniy:
                if self.counter < 3:
                    return
                else:
                    self.counter = 0
            if self.movanix:
                if self.spritenum == 3:
                    self.spritenum = 1
                else:
                    self.spritenum += 1
                if self.movanix > 0:
                    self.movanix -= 32/4
                    self.sprite = "pl" + str(self.spritenum)
                elif self.movanix < 0:
                    self.movanix += 32/4
                    self.sprite = "pr" + str(self.spritenum)
                if self.movanix == 0:
                    self.movanix = False
            elif self.movaniy:
                if self.spritenum == 3:
                    self.spritenum = 1
                else:
                    self.spritenum += 1
                if self.movaniy > 0:
                    self.movaniy -= 32/4
                    self.sprite = "pu" + str(self.spritenum)
                elif self.movaniy < 0:
                    self.movaniy += 32/4
                    self.sprite = "pd" + str(self.spritenum)
                if self.movaniy == 0:
                    self.movaniy = False
            else:
                key = pygame.key.get_pressed()
                if key[K_a] or key[K_LEFT]:
                    direction = 'l'
                elif key[K_d] or key[K_RIGHT]:
                    direction = 'r'
                elif key[K_w] or key[K_UP]:
                    direction = 'u'
                elif key[K_s] or key[K_DOWN]:
                    direction = 'd'
                else:
                    return
                    
                if direction == 'l':
                    dest = vars.dung.get(self.x - 1, self.y)
                elif direction == "r":
                    dest = vars.dung.get(self.x + 1, self.y)
                elif direction == "u":
                    dest = vars.dung.get(self.x, self.y - 1)
                elif direction == "d":
                    dest = vars.dung.get(self.x, self.y + 1)

                self.sprite = "p" + direction + str(self.spritenum)
                if dest:
                    if dest.type == "portal":
                        self.movanix = False
                        self.movaniy = False
                        x = dest.destpos[0]
                        y = dest.destpos[1]
                        vars.dung.change(dest.dest)
                        self.x = x
                        self.y = y
                        if len(box.groups[0].sprites()) > 0:
                            vars.panelupdate = True
                        [ bla.empty() for bla in box.groups ]
                        return
                    elif dest.type == "floor" or dest.type == "pot":
                        if len(box.groups[0].sprites()) > 0:
                            vars.panelupdate = True
                        [ bla.empty() for bla in box.groups ]
                        if direction == "l":
                            self.x -= 1
                            self.movanix = 32*3/4
                        elif direction == "r":
                            self.x += 1
                            self.movanix = -(32*3/4)
                        elif direction == "u":
                            self.y -= 1
                            self.movaniy = 32*3/4
                        elif direction == "d":
                            self.y += 1
                            self.movaniy = -(32*3/4)
        
    def msgBox(self, coor):
        box(self, coor, ['', 'cancel'])
            
    def damage(self, hp):
        self.hp = self.hp - hp
        if self.hp < 1:
            return False
        return True
        
    def attack(self, charr):
        #Check for hit
        chance = self.dex*1.0 / charr.dex / 2.0
        if chance > random():
            dmg = self.str + random()*pow(self.lvl,3)
            if self.eq['weapon']:
                dmg += self.eq['weapon'].power
            defe = random()*pow(charr.lvl,3)
            power = (dmg - defe)/4
            if power < self.lvl*2:
                power = self.lvl*2.0 - charr.lvl/2.0
            power = int(power)
            if not charr.damage(power):
                #exp sys
                vars.player.exp += charr.exp
                return "dead"
            return power
        return False

class char():
    def __init__(self, name, sprite):
        self.name = name
        self.sprite = sprite
        self.x = 0
        self.y = 0
        self.lvl = 1
        self.str = 10
        self.exp = 10
        self.gold = 0
        self.dex = 10
        self.hp = 10
        self.type = "char"

    def damage(self, hp):
        self.hp = self.hp - hp
        if self.hp < 1:
            return False
        return True
        
    def attack(self, char):
        chance = self.dex*1.0 / char.dex / 2.0
        if chance > random():
            dmg = self.str + random()*pow(self.lvl,3)
            defe = random()*pow(char.lvl,3)
            if char.eq['armor']:
                defe += char.eq['armor'].power
            if char.eq['head']:
                defe += char.eq['head'].power
            power = (dmg - defe)/4
            if power < self.lvl*2:
                power = self.lvl*2.0 - char.lvl/2.0
            power = int(power)
            if not char.damage(power):
                return "dead"
            return power
        return False
    
    def msgBox(self, coor):
        box(self, coor, ['kill', 'cancel'])
        
class wall():
    def __init__(self,sprite,transparent=False):
        self.sprite = sprite
        self.transparent = transparent
        self.type = "wall"

    def click(self):
        pass

    def msgBox(self, pos):
        pass

class floor():
    def __init__(self,sprite):
        self.sprite = sprite
        self.type = "floor"

    def click(self):
        pass

    def msgBox(self, pos):
        pass
        
class portal():
    def __init__(self,sprite,dest,destpos):
        self.sprite = sprite
        self.dest = dest
        self.destpos = destpos
        self.type = "portal"

    def click(self):
        pass

    def msgBox(self, pos):
        pass

"""class msgNpc():
    def __init__(self,name,sprite,msg):
        self.name = name
        self.sprite = sprite
        self.msg = msg
        self.type = 'msgNpc'

    def draw(self, dest):
        dest.blit(img('msgNpc'), (0,0))
        printSurface(dest, lang[self.name], 40, colors.grey, (16*27, 150), True)
        printSurface(dest, lang['anyKey'], 20, colors.grey, (16*27, 670), True)

        rect = pygame.Rect(20,190,27*32-40,450)
        if vars.debug:
            pygame.draw.line(dest, (200,200,200), (rect.x,rect.y), (rect.x+rect.w,rect.y))
            pygame.draw.line(dest, (200,200,200), (rect.x,rect.y), (rect.x,rect.y+rect.h))
            pygame.draw.line(dest, (200,200,200), (rect.x+rect.w,rect.y), (rect.x+rect.w,rect.y+rect.h))
            pygame.draw.line(dest, (200,200,200), (rect.x,rect.y+rect.h), (rect.x+rect.w,rect.y+rect.h))

        size = 14
        font = pygame.font.Font(vars.font, size)
        lines = fitInRect(lang[self.msg], font, rect)
        x = 0
        offset = (rect.h - len(lines)*(size+5))/3
        for msg in lines:
            printSurface(dest, msg, size, colors.grey, (16*27, 200+x*(size+5)+offset), True)
            x+= 1"""
            
class readbook():
    def __init__(self,name,sprite,msg):
        self.name = name
        self.sprite = sprite
        self.msg = msg
        self.type = 'readbook'
    
    def click(self, dung=None):
        pass
    
    def msgBox(self, coor):
        box(self, coor, ['', 'cancel'])

        
class lock():
    """ob - lista wspolzednych obiektow do sprawdzenia, jezeli nie sa charami, to lock jest zastepowany repem
       rep - obiekt zastepujacy (najczesciej portal albo podloga)"""
    def __init__(self,name,sprite,ob,rep):
        self.sprite = sprite
        self.name = name
        self.ob = ob
        self.rep = rep
        self.type = "lock"
            
    def msgBox(self, coor):
        box(self, coor, ['', 'cancel'])

class dungeon():
    def __init__(self):
        self.dungeons = cPickle.load(open('dungs.upf'))
        self.dung = self.dungeons[0][0]
        self.floor = self.dungeons[0][1]
        
    def get(self, x, y):
        return self.dung[y][x]

    def update(self):
        ## LOCKS and bigSprites ##
        y = 0
        for rows in self.dung:
            x = 0
            for item in rows:
                if item:
                    if item.type == 'lock':
                        for pos in item.ob:
                            if not self.get(pos[0], pos[1]):
                                item.ob.remove(pos)
                            elif not self.get(pos[0], pos[1]).type == 'char':
                                item.ob.remove(pos)

                        if len(item.ob) == 0:
                            self.set(item.rep, x, y)
                    elif item.type == 'bigSprite':
                        item.update()
                x += 1
            y += 1

    def set(self, ob, x, y):
        self.dung[y][x] = ob
        self.update()
        self.regenerate()
        
    def regenerate(self):
        surface = pygame.Surface(((len(self.dung[0]))*32,((len(self.dung))*32)))
        for y in range(len(self.dung)):
            for x in range(len(self.dung[0])):
                if self.dung[y][x] and (not self.dung[y][x].type == 'wall' or self.dung[y][x].transparent):
                    surface.blit(img(self.floor), ((x)*32,(y)*32))
                
        y = 0
        for row in self.dung:
            x = 0
            for item in row:
                if not item:
                    surface.blit(img('black'), (x*32,y*32))
                    x += 1
                    continue
                elif item.type == 'bigSprite':
                    if not images.__contains__(item.sprite):
                        sprite = pygame.Surface((32,32))
                        sprite.blit(img(self.floor), (0,0))
                        sprite.blit(img(item.parent.sprite), (0,0), (item.x*32-item.parent.x*32,item.y*32-item.parent.y*32,32,32))
                        images[item.sprite] = sprite
                elif item.type == 'floor' and item.sprite == self.floor:
                    x += 1
                    continue
                surface.blit(img(item.sprite), (x*32,y*32))
                x += 1
            y += 1

        self.img = surface
        return surface

    def replace(self, ob1, ob2):
        y = 0
        for row in self.dung:
            x = 0
            for item in row:
                if item == ob1:
                    self.set(ob2, x, y)
                x+= 1
            y += 1
        
    def change(self, dest):
        self.dung = self.dungeons[dest][0]
        self.floor = self.dungeons[dest][1]
        self.img = self.regenerate()

class Menu():
    def __init__(self):
        self.img = img('menu')
        self.pos = 0
        
    def draw(self, dest):
        dest.blit(self.img, (0,0))
        lang = langs[vars.language]
        if vars.shadow:
            shadow = 'on'
        else:
            shadow = 'off'
            
        options = [ lang['play'],
                    lang['load'],
                    lang['save'],
                    lang['language']+lang[vars.language],
                    lang['shadow']+lang[shadow],
                    lang['exit'],
                  ]
        printSurface(dest, options[self.pos], 50, colors.menusel, (27*16, 225+self.pos*75), True)
        options[self.pos] = False
        x = 0
        for option in options:
            if option:
                printSurface(dest, option, 40, colors.menu, (27*16, 225+x*75), True)
            x += 1

    def click(self, key):
        global lang
        if key == K_UP or key == K_w:
            self.pos -= 1
            if self.pos < 0:
                self.pos = 5
        elif key == K_DOWN or key == K_s:
            self.pos += 1
            if self.pos > 5:
                self.pos = 0
        elif key == K_LEFT or key == K_a:
            if self.pos == 3:
                cur = vars.supported_languages.index(vars.language)
                if cur == 0:
                    lan = len(vars.supported_languages)-1
                else:
                    lan = cur-1
                vars.language = vars.supported_languages[lan]
                lang = langs[vars.language]
            elif self.pos == 4:
                vars.shadow = not vars.shadow
        elif key == K_RIGHT or key == K_d:
            if self.pos == 3:
                cur = vars.supported_languages.index(vars.language)
                if cur == len(vars.supported_languages)-1:
                    lan = 0
                else:
                    lan = cur+1
                vars.language = vars.supported_languages[lan]
                lang = langs[vars.language]
            elif self.pos == 4:
                vars.shadow = not vars.shadow
        elif key == K_RETURN:
            if self.pos == 1:
                lang = langs[vars.language]
            elif self.pos == 5:
                pygame.quit()
                sys.exit()
